package com.qys.livesMall.app.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qys.livesMall.app.user.event.AppUserWithdrawalEvent;
import com.qys.livesMall.app.user.mapper.H2AppUserRechargeWithdrawalsMapper;
import com.qys.livesMall.app.user.mapper.UserShopStatisticsMapper;
import com.qys.livesMall.app.user.model.dto.app.AppUserApplyWithdrawalDTO;
import com.qys.livesMall.app.user.model.dto.sys.*;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.app.user.model.entity.UserShopStatistics;
import com.qys.livesMall.app.user.model.entity.UserStatisticsTeam;
import com.qys.livesMall.app.user.model.entity.UserStatisticsInfo;
import com.qys.livesMall.app.user.mapper.UserStatisticsInfoMapper;
import com.qys.livesMall.app.user.model.vo.sys.H2ShopStatisticsInfoVo;
import com.qys.livesMall.app.user.model.vo.sys.SysUserStatisticsVo;
import com.qys.livesMall.app.user.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.common.utils.DateUtils;
import com.qys.livesMall.finance.enums.AccountBusinessTypeEnum;
import com.qys.livesMall.finance.model.dto.user.FinanceUserAccountDTO;
import com.qys.livesMall.finance.model.dto.user.UserIncomeDayDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户统计表 服务实现类
 * </p>
 *
 * @author 
 * @since 2023-08-01
 */
@Slf4j
@Service
public class UserStatisticsInfoServiceImpl extends ServiceImpl<UserStatisticsInfoMapper, UserStatisticsInfo> implements UserStatisticsInfoService {

    @Resource
    private UserShopStatisticsMapper userShopStatisticsMapper;
    @Resource
    private UserStatisticsTeamService userStatisticsTeamService;
    @Resource
    private IH2AppUserService ih2AppUserService;
    @Resource
    private AppUserRelationService relationService;
    @Resource
    private H2AppUserRechargeWithdrawalsMapper appUserRechargeWithdrawalsMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatebyUserid(UserRechargeDTO userRechargeDTO) {
        log.info("充值提现监听 UserRechargeDTO：{}",userRechargeDTO);
        UserStatisticsInfo userStatisticsInfo=baseMapper.selectByUserId(userRechargeDTO.getUserId());
        if (null == userStatisticsInfo){
         return false;
        }
        //用户共同信息
        UserShopStatistics userShopStatistics=userShopStatisticsMapper.selectByUserId(userStatisticsInfo.getUserId());
        //获取用户团信息
        List<UserStatisticsTeam> userStatisticsTeamList = userStatisticsTeamService.getByTeamId(userShopStatistics.getTeamId());
        UserStatisticsTeam userStatisticsTeam = userStatisticsTeamList.get(0);
        //ShopBusinessTypeEnum
        if (userRechargeDTO.getType().equals("re")){
            //充值
            if (null==userStatisticsInfo.getRecharge()){
                userStatisticsInfo.setRecharge(BigDecimal.ZERO);
            }
            BigDecimal recharge=userStatisticsInfo.getRecharge().add(userRechargeDTO.getRealAmount());
            userStatisticsInfo.setRecharge(recharge);
            userStatisticsTeam.setIsRecharge(1);
            userStatisticsInfo.setRechargeNumber(userStatisticsInfo.getRechargeNumber()+1);
            if (userStatisticsInfo.getRechargeNumber()==2){
                userStatisticsInfo.setRechargeMoney(userRechargeDTO.getRealAmount());
            }
            userStatisticsTeam.setTeamRecharge(userStatisticsTeam.getTeamRecharge().add(userRechargeDTO.getRealAmount()));
            //判断用户是不是第一次充值
            if (null == userStatisticsInfo.getFirstCharge()){
                userStatisticsInfo.setFirstCharge(DateUtils.dateTimeNow());
                //团人数修改
                userStatisticsTeam.setNum(userStatisticsTeam.getNum()+1);
                H2AppUser h2AppUser=ih2AppUserService.getById(userRechargeDTO.getUserId());
                if (h2AppUser.getStatus()==0 && h2AppUser.getUserSysType()==1 && h2AppUser.getUserLevelId().intValue()<=3){
                    userStatisticsTeam.setRecentAdd(userStatisticsTeam.getRecentAdd()==null?1: userStatisticsTeam.getRecentAdd()+1);
                    userStatisticsInfo.setRecentAdd(userStatisticsInfo.getRecentAdd() ==null?1:userStatisticsInfo.getRecentAdd()+1);
                }
                if (h2AppUser.getUserLevelId()>=1){
                    Long userId=userRechargeDTO.getUserId();
                    //更新上3级数据
                    for (int i = 0; i < 3; i++) {
                        H2AppUser h2AppUser1=ih2AppUserService.getById(userId);
                        if (null == h2AppUser1.getSuperior()){
                            break;
                        }
                        userId=h2AppUser1.getSuperior();
                        UserStatisticsInfo oneUserStatistics=baseMapper.selectByUserId(h2AppUser1.getSuperior());
                        if (i == 0){
                            oneUserStatistics.setDirectNumber(oneUserStatistics.getDirectNumber()==null?1:oneUserStatistics.getDirectNumber()+1);
                        }
                        if (i == 1){
                            oneUserStatistics.setTwoNumber(oneUserStatistics.getTwoNumber()==null?1:oneUserStatistics.getTwoNumber()+1);
                        }
                        if (i == 2){
                            oneUserStatistics.setThreeNumber(oneUserStatistics.getThreeNumber()==null?1:oneUserStatistics.getThreeNumber()+1);
                        }
                        if (null == oneUserStatistics.getThreeWithdrawalAmount()){
                            oneUserStatistics.setThreeWithdrawalAmount(BigDecimal.ZERO);
                        }
                        updateById(oneUserStatistics);
                    }
                }
            }
        }else {
            //提现
            if (null == userStatisticsInfo.getWithdrawal()){
                userStatisticsInfo.setWithdrawal(BigDecimal.ZERO);
            }
            userStatisticsInfo.setPendingWithdrawal(userStatisticsInfo.getPendingWithdrawal().subtract(userRechargeDTO.getRealAmount()));
            BigDecimal withdrawal=userStatisticsInfo.getWithdrawal().add(userRechargeDTO.getRealAmount());
            userStatisticsInfo.setWithdrawal(withdrawal);
            userStatisticsInfo.setWithdrawalNumber(userStatisticsInfo.getWithdrawalNumber()+1);
            //团数据变更
            userStatisticsTeam.setTeamWithdrawal(userStatisticsTeam.getTeamWithdrawal().add(userRechargeDTO.getRealAmount()));
            userStatisticsTeam.setWaitWithdrawal(userStatisticsTeam.getWaitWithdrawal().subtract(userRechargeDTO.getRealAmount()));
        }
        //充提差额
        userStatisticsInfo.setDifference(userStatisticsInfo.getRecharge().subtract(userStatisticsInfo.getWithdrawal()));
        userStatisticsTeam.setTeamDifference(userStatisticsTeam.getTeamRecharge().subtract(userStatisticsTeam.getTeamWithdrawal()));
        log.info("充值提现监听 userStatisticsInfo：{}",userStatisticsInfo);
        baseMapper.updateById(userStatisticsInfo);
        userStatisticsTeamService.updateById(userStatisticsTeam);
        return true;
    }

    @Override
    public boolean updateBalance(FinanceUserAccountDTO financeUserAccountDTO) {
        UserStatisticsInfo userStatisticsInfo=baseMapper.selectByUserId(financeUserAccountDTO.getUserId());
        if (null == userStatisticsInfo){
            return false;
        }
        userStatisticsInfo.setBalance(financeUserAccountDTO.getAvailableBalance());
        updateById(userStatisticsInfo);
        UserShopStatistics userShopStatistics=userShopStatisticsMapper.selectByUserId(userStatisticsInfo.getUserId());
        //获取用户团信息
        List<UserStatisticsTeam> userStatisticsTeamList = userStatisticsTeamService.getByTeamId(userShopStatistics.getTeamId());
        UserStatisticsTeam userStatisticsTeam = userStatisticsTeamList.get(0);
        if (null != userStatisticsTeam){
            if (null==userStatisticsTeam.getTeamBalance()){
                userStatisticsTeam.setTeamBalance(BigDecimal.ZERO);
            }
            userStatisticsTeam.setTeamBalance(userStatisticsTeam.getTeamBalance().add(financeUserAccountDTO.getAvailableBalance()));
        }
        //30天过期  人数3级内 余额小于20+真实用户+状态正常+充值用户
        //余额变更 类型：0 收入 1 支出
        if ( financeUserAccountDTO.getType() == 0){
            if (financeUserAccountDTO.getUnchangedAvailableBalance().compareTo(new BigDecimal(20)) < 0
                    && financeUserAccountDTO.getAvailableBalance().compareTo(new BigDecimal(20)) >= 0){
                updateExpireNumber(financeUserAccountDTO.getUserId(),financeUserAccountDTO.getType());
            }
        }else {
            if (financeUserAccountDTO.getUnchangedAvailableBalance().compareTo(new BigDecimal(20)) >= 0
                    && financeUserAccountDTO.getAvailableBalance().compareTo(new BigDecimal(20)) < 0){
                updateExpireNumber(financeUserAccountDTO.getUserId(),financeUserAccountDTO.getType());
            }
        }
        return true;
    }

    public void updateExpireNumber(Long userId,int type){
        H2AppUser h2AppUser = ih2AppUserService.getById(userId);
        if (h2AppUser.getUserLevelId().intValue() <= 3
                && h2AppUser.getUserSysType() == 1
                && h2AppUser.getStatus()== 0 ){
            //更新上3级数据
            if (null != h2AppUser.getSuperior()){
                String superior=String.valueOf(h2AppUser.getSuperior());
                for (int i = 0; i < 3; i++) {
                    UserShopStatistics  oneUser = userShopStatisticsMapper.getbyUserName(superior);
                    if (null==oneUser){
                        break;
                    }
                    UserStatisticsInfo oneUserStatistics=baseMapper.selectByUserId(oneUser.getUserId());
                    if (type==0){
                        oneUserStatistics.setExpireNumber(oneUserStatistics.getExpireNumber()==null?0:oneUserStatistics.getExpireNumber()-1);
                        oneUserStatistics.setRecentExpireNumber(oneUserStatistics.getExpireNumber()==null?0:oneUserStatistics.getExpireNumber()-1);
                    }else {
                        oneUserStatistics.setExpireNumber(oneUserStatistics.getExpireNumber()==null?1:oneUserStatistics.getExpireNumber()+1);
                        oneUserStatistics.setRecentExpireNumber(oneUserStatistics.getRecentExpireNumber()==null?0:oneUserStatistics.getRecentExpireNumber()+1);

                    }
                    updateById(oneUserStatistics);

                    List<UserStatisticsTeam> userStatisticsTeamList = userStatisticsTeamService.getByTeamId(oneUser.getTeamId());
                    if (CollectionUtils.isNotEmpty(userStatisticsTeamList)){
                        UserStatisticsTeam userStatisticsTeam = userStatisticsTeamList.get(0);
                        if (type==0){
                            userStatisticsTeam.setExpireNumber(userStatisticsTeam.getExpireNumber()==null?0: userStatisticsTeam.getExpireNumber()-1);
                            userStatisticsTeam.setExpireRecent(userStatisticsTeam.getExpireRecent()==null?0: userStatisticsTeam.getExpireRecent()-1);
                        }else {
                            userStatisticsTeam.setExpireNumber(userStatisticsTeam.getExpireNumber()==null?1: userStatisticsTeam.getExpireNumber()+1);
                            userStatisticsTeam.setExpireRecent(userStatisticsTeam.getExpireRecent()==null?1: userStatisticsTeam.getExpireRecent()+1);
                        }
                        userStatisticsTeamService.updateById(userStatisticsTeam);
                    }
                    if (null != oneUserStatistics.getSuperior()){
                        superior=oneUserStatistics.getSuperior();
                    }
                }
            }
        }
    }

    @Override
    public UserStatisticsInfo selectByUserId(Long userId) {
        LambdaQueryWrapper<UserStatisticsInfo> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserStatisticsInfo::getUserId,userId);
        List<UserStatisticsInfo> userStatisticsInfo=list(lambdaQueryWrapper);
        if (CollectionUtils.isNotEmpty(userStatisticsInfo)){
            return userStatisticsInfo.get(0);
        }
        return null;
    }

    @Override
    public Page<SysUserStatisticsVo> pageSys(SysUserStatisticsPageDTO pageDTO) {

        if (StringUtils.isNoneEmpty(pageDTO.getSuperior())){
            H2AppUser h2AppUser = ih2AppUserService.getUserByRandomId(pageDTO.getSuperior());
            if (null == h2AppUser){
                return new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize());
            }
            List<String> list=ih2AppUserService.getsubsetList(h2AppUser.getId());
            if (CollectionUtils.isEmpty(list)){
                //条件不符合，直接返回
                return new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize());
            }
            pageDTO.setUserIds(list.stream().map(a->Long.valueOf(a)).collect(Collectors.toList()));
        }
        if (StringUtils.isNotBlank(pageDTO.getUserDirectPush()) || StringUtils.isNotBlank(pageDTO.getUser3rdGeneration()) || StringUtils.isNotBlank(pageDTO.getUserUnderUmbrella())){
            List<Long> userIds=null;
            if (StringUtils.isNotBlank(pageDTO.getUserDirectPush())){
                //直推
                userIds=relationService.getLowerLevels(pageDTO.getUserDirectPush(),1);
            }else if (StringUtils.isNotBlank(pageDTO.getUser3rdGeneration())){
                //三代
                userIds=relationService.getLowerLevels(pageDTO.getUser3rdGeneration(), Arrays.asList(1,2,3));
            }else if (StringUtils.isNotBlank(pageDTO.getUserUnderUmbrella())){
                //伞下
                userIds=relationService.getGreaterLevels(pageDTO.getUserUnderUmbrella(),0);
            }
            //查询真实用户，状态正常，充值用户
            if (CollectionUtils.isNotEmpty(userIds)){
                userIds=relationService.getValidUser(userIds);
            }
            if (CollectionUtils.isEmpty(userIds)){
                return new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize());
            }
            pageDTO.setUserIds(userIds);
        }
        Page<SysUserStatisticsVo> page = new Page<>(pageDTO.getPageNum(), pageDTO.getPageSize());
        page=baseMapper.pageSys(page,pageDTO);
        return page;
    }

    @Override
    public List<UserStatisticsInfo> getListByUserid(List<Long> userids) {
       return baseMapper.getListByUserid(userids);
    }

    @Override
    public List<H2ShopStatisticsInfoVo> getShopListByUserid(List<Long> userids) {
        return baseMapper.getShopListByUserid(userids);
    }

    @Override
    public Boolean addUserNotes(UserNotesAddDTO userNotesAddDTO) {
        UserStatisticsInfo userStatisticsInfo=baseMapper.selectByUserId(userNotesAddDTO.getUserId());
        if (null == userStatisticsInfo){
            return false;
        }
        if (userNotesAddDTO.getType() == 0){
            userStatisticsInfo.setNotes(userNotesAddDTO.getNotes());
            baseMapper.updateById(userStatisticsInfo);
            return true;
        }
        List<String> userIds = ih2AppUserService.gettreeList(userNotesAddDTO.getUserId().toString(),3,null);
        userShopStatisticsMapper.updateNotesbyUserids(userIds,userNotesAddDTO.getNotes());
        return true;
    }

    @Override
    public void updateUserSuperior(Long userId) {
        BigDecimal resutlt=appUserRechargeWithdrawalsMapper.getRechargeAmount(Arrays.asList(userId));
        if (resutlt ==null || resutlt.compareTo(BigDecimal.ZERO)<=0){
            return;
        }
        //更新上3级数据
        for (int i = 0; i < 3; i++) {
            H2AppUser h2AppUser=ih2AppUserService.getById(userId);
            if (null == h2AppUser.getSuperior()){
                break;
            }
            userId=h2AppUser.getSuperior();
            UserStatisticsInfo oneUserStatistics=baseMapper.selectByUserId(h2AppUser.getSuperior());
            if (i == 0){
                oneUserStatistics.setDirectNumber(oneUserStatistics.getDirectNumber()==null?1:oneUserStatistics.getDirectNumber()+1);
            }
            if (i == 1){
                oneUserStatistics.setTwoNumber(oneUserStatistics.getTwoNumber()==null?1:oneUserStatistics.getTwoNumber()+1);
            }
            if (i == 2){
                oneUserStatistics.setThreeNumber(oneUserStatistics.getThreeNumber()==null?1:oneUserStatistics.getThreeNumber()+1);
            }
            if (null == oneUserStatistics.getThreeWithdrawalAmount()){
                oneUserStatistics.setThreeWithdrawalAmount(BigDecimal.ZERO);
            }
            updateById(oneUserStatistics);
        }
    }

    @Override
    public void updateAnchorIncome(UserIncomeDayDTO userIncomeDayDTO) {
        UserStatisticsInfo userStatisticsInfo=baseMapper.selectByUserId(userIncomeDayDTO.getRelevanceId());
        if (userIncomeDayDTO.getCode().equals(AccountBusinessTypeEnum.ORDER_PROFIT_ANCHOR_GET.getCode())){
            userStatisticsInfo.setAnchorOrderIncome(userStatisticsInfo.getAnchorOrderIncome()==null?userIncomeDayDTO.getTodayincome()
                    :userStatisticsInfo.getAnchorOrderIncome().add(userIncomeDayDTO.getTodayincome()));
        }
        if (userIncomeDayDTO.getCode().equals(AccountBusinessTypeEnum.LIVE_GIFT_ANCHOR_GET.getCode())){
            userStatisticsInfo.setAnchorGiftIncome(userStatisticsInfo.getAnchorGiftIncome()==null?userIncomeDayDTO.getTodayincome()
                    :userStatisticsInfo.getAnchorGiftIncome().add(userIncomeDayDTO.getTodayincome()));
        }
        baseMapper.updateById(userStatisticsInfo);
    }

    @Override
    public void updatePendingWithdrawal(AppUserApplyWithdrawalDTO appUserApplyWithdrawalDTO) {
        UserStatisticsInfo userStatisticsInfo=baseMapper.selectByUserId(Long.valueOf(appUserApplyWithdrawalDTO.getUserId()));
        if (appUserApplyWithdrawalDTO.getType()==1){
            userStatisticsInfo.setPendingWithdrawal(userStatisticsInfo.getPendingWithdrawal().add(appUserApplyWithdrawalDTO.getAmount()));
        }else {
            userStatisticsInfo.setPendingWithdrawal(userStatisticsInfo.getPendingWithdrawal().subtract(appUserApplyWithdrawalDTO.getAmount()));
        }
        updateById(userStatisticsInfo);
    }
}
